//
//  WXObject.m
//  技术点总结
//
//  Created by tianlong on 2018/6/12.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "WXObject.h"
#import <objc/runtime.h>

@implementation WXObject
- (id)copyWithZone:(NSZone *)zone {
    return [self wx_copyWithZone:zone];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [self wx_copyWithZone:zone];
}

- (id)wx_copyWithZone:(NSZone *)zone {
    id obj = [[self class] allocWithZone:zone];
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = *(ivars + i);
        
        // 获取成员类型
        const char *type = ivar_getTypeEncoding(ivar);
        NSString *var_type = [NSString stringWithUTF8String:type];
        var_type = [var_type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        var_type = [var_type stringByReplacingOccurrencesOfString:@"@" withString:@""];
        
        // 获取成员属性名
        const char *varName = ivar_getName(ivar);
        NSString *var_keypath = [NSString stringWithUTF8String:varName];
        var_keypath = [var_keypath stringByReplacingOccurrencesOfString:@"_" withString:@""];
        //NSLog(@"var_type = %@ var_keypath = %@",var_type,var_keypath);
        
        Class ivarClass = NSClassFromString(var_type);
        if ([ivarClass isKindOfClass:[NSObject class]]) {
            id temp = [self valueForKeyPath:var_keypath];
            if ([temp conformsToProtocol:@protocol(NSCopying)]) {
                [obj setValue:[temp copy] forKeyPath:var_keypath];
            }else if([temp conformsToProtocol:@protocol(NSMutableCopying)]){
                [obj setValue:[temp mutableCopy] forKeyPath:var_keypath];
            }
        }else {
            if (var_keypath) {
                [obj setValue:[self valueForKeyPath:var_keypath] forKeyPath:var_keypath];
            }
        }
    }
    free(ivars);
    return obj;
}


@end
